package com.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;

import java.nio.charset.Charset;



class RecvMessageFromBrower extends SimpleChannelInboundHandler<DefaultHttpRequest>{



    @Override
    protected void channelRead0(ChannelHandlerContext context, DefaultHttpRequest request) throws Exception {
        String uri = request.uri();
        int index = uri.lastIndexOf('?');
        if (index>-1)
        {
            //接收地址信息，并解析
            String queryString = uri.substring(index+1);
            String[] arrs = queryString.split("&");
            String param1 = arrs[0];//x=1
            String param2 = arrs[1];//y=2
            int x =  Integer.parseInt( param1.split("=")[1] );
            int y =  Integer.parseInt( param2.split("=")[1] );
            int z = x+y;
            String responseStr = "<h1>"+z+"";
            //发送到客户端
            ByteBuf conent = Unpooled.wrappedBuffer(responseStr.getBytes(Charset.defaultCharset()));
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,conent);
            context.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);;

        }
    }
}

class HttpClientHandler extends ChannelInitializer {

    @Override
    protected void initChannel(Channel channel) throws Exception {
        System.out.println("客户端来请求了");
        channel.pipeline().addLast(new HttpServerCodec());
        channel.pipeline().addLast(new RecvMessageFromBrower());
    }
}

public class NettyTomcat {

    public static void main(String[] args) throws InterruptedException {
        //1.引导器
        ServerBootstrap  b = new ServerBootstrap();
        //2.事件组
        EventLoopGroup  bossGroup = new NioEventLoopGroup();
        EventLoopGroup  workGroup = new NioEventLoopGroup();
        b.group(bossGroup,workGroup);
        //3.设置通道类型
        b.channel(NioServerSocketChannel.class);
        //4.监听客户端连接
        b.childHandler(new HttpClientHandler());
        //5.启动服务器并绑定端口
        ChannelFuture  cf =  b.bind(9090).sync();
        //6.等待关闭
        cf.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();


    }
}
